<?php

require_once 'Zend/Controller/Action/Helper/Abstract.php';

class Zen_Controller_Action_Helper_Jqgrid extends Zend_Controller_Action_Helper_Abstract{
	
	protected $params = array();
	
	protected $model = null;
	
	public $suppressExit = false;
	
	protected $id_prefix = 'pr_';
	
	protected $jqgrid_search = array ("eq" => "= '?'", "ne" => "<> '?'", "lt" => "< '?'", "le" => "<= '?'", "gt" => "> '?'", "ge" => ">= '?'", "bw" => "LIKE '?%'", "bn" => "NOT LIKE '?%'", "in" => "IN(?)", "ni" => "NOT IN(?)", "ew" => " LIKE '%?'", "en" => "NOT LIKE '%?'", "cn" => "LIKE '%?%'", "nc" => "NOT LIKE '%?%'" );
	
	private function sendJson($data, $keepLayouts = false) {
        $data = $this->encodeJson($data, $keepLayouts);
        $response = $this->getResponse();
        $response->setBody($data);
        if (!$this->suppressExit) {
            $response->sendResponse();
            exit;
        }
        return $data;
    }
	
	public function encodeJson($data, $keepLayouts = false) {
        require_once 'Zend/View/Helper/Json.php';
        $jsonHelper = new Zend_View_Helper_Json();
        $data = $jsonHelper->json($data, $keepLayouts);
        if (!$keepLayouts) {
            require_once 'Zend/Controller/Action/HelperBroker.php';
            Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        }
        return $data;
    }
    
    public function log($message, $priority = null, $params = null) {
    	if (! $params)  $params = array();
    	$model = $this->model;
    	if ($model->isAllowLog()) 
    		$params['addition'] = serialize( $this->params );
    	if (! $priority) 	$priority = Zend_Log::NOTICE;
    	$params['resource'] = $model->getTableName();
    	Log_Model_Logger::log($message, $priority, $params);
    	return $this;
    }
    
	public function direct($model, $params, $columns, $form = false, $select = false, $sendNow = true, $keepLayouts = false){
		$this->params = $params;
		$this->model = $model;
		$operation=(isset($params['operation'])) ? $params['operation'] : null;
    	unset($params['operation']);
    	$controler = $this->getActionController();
    	$data=array('status'=>0);
    	switch ($operation) {
    		case 'read':{
	    		$response = array ();
	    		if (! $select) $select = $model->select();
	    		$select->setPaging(true);
	    		
	    		$added_where = $select->getWhere();
	    		
	    		if ( (isset($params['sidx']) && $params['sidx'] !='id') || (! $select->getOrder() && isset($params['sidx']) && $params['sidx'] =='id') ) {
	    			if (isset($params['sidx']) && isset($params['sord'])) $select->setOrder($params['sidx'].' '.$params['sord'] );
	    		}
	    		if (isset($params['page'])) $select->setPage($params['page']);
	    		if (isset($params['rows'])) $select->setLimit($params['rows']);
	    		
	    		$searchwhere = '';
	    		
		    	if((isset($params['_search']))
		    		&& ($params['_search']=='true')
		    		&& (isset($params['searchField']))
		    		&& (isset($params['searchOper']))
		    		&& (isset($params['searchString']))
		    		){
		    		$field = $params['searchField'];
					$eq = $this->jqgrid_search [$params['searchOper']];
					$val = $params['searchString'];
					$searchwhere = $field . " " . $eq;
					$searchwhere = preg_replace ( '/\?/', $val, $searchwhere );
					$added_where = ( $added_where ) ? " and $added_where" : '';
		        }
	    		$select->setWhere( $searchwhere . $added_where );
				$res = $select->getData();
				$data ['records'] = $select->getTotalcount ();
				$data ['page'] = $select->getPage ();
				$data ['total'] = $select->getPagecount ();
				if (sizeof ( $res ) > 0) {
					foreach ( $res as $row ) {
						$cell = array ();
						foreach ( $columns as $col )
							$cell [] = $row [$col ['index']];
						$data ['rows'] [] = array ('id' => $this->id_prefix . $model->getTableName() .'_'. $row ['id'], 'cell' => $cell );
					}
				}
				$data['status'] = 1;
		        if ($sendNow) return $this->sendJson($data, $keepLayouts);
		        else 	      return $data;
    		}
    		case 'delete':{
    			if ( null !== $params['id'] ) {
	    			$id=preg_replace('/\D/','',$params['id']);
	                $res=$model->delete($id);
	                $this->log('Deleting '.$id);
	                $data['status'] = ($res) ? 1 : 0;
			        if ($sendNow)	return $this->sendJson($data, $keepLayouts);
			        else	        return $data;
    			}
    		}
    		default: {
				//$controler->getHelper('layout')->setLayout ( 'iframe' );
				$mode = 'create';
				$controler->view->title = 'Добавление';
				if ( isset( $params['id'] )) {
					$id = preg_replace ( '/\D/', '', $params['id'] );
					$item = $model->read ( "`id`='" . $id . "'" );
					if ($item) {
						$form->setDefaults ( $item );
						$mode = 'update';
						$controler->view->item = $item;
						$controler->view->title = 'Редактирование';
					}
				}
				if ($controler->getRequest()->isPost ()) {
					
					if ($form->isValid ( $params )) {
						$params = $form->getValues ();
						$params=$form->getValues();
						if(sizeof($form->getSubForms())>0){
							$data=array();
							foreach ($form->getSubForms() as $subform)
								$data=array_merge($data,$params[$subform->getName()]);
							$params=$data;
						}
						
						if ($mode == 'create'){
							$id = $model->create ( $params );
							$this->log('Creating');
							$message = 'Добавление данных ';
						}
						if ($mode == 'update'){
							$model->update ($id,$params);
							$this->log('Updating '.$id);
							$message = 'Обновление данных ';
						}
						$data = array ();
						if ($id) {
							$data ['id'] = $id;
							$rec = $model->read("`id` = $id");
							if($rec!=false){
								$st = new Zend_Filter_StripTags();
								$record = array();
								foreach ( $columns as $col )
									$record[$col['name']] = $st->filter($rec[$col['name']]);
								$data ['status'] = 1;
								$data ['record']= array('id' => $this->id_prefix . $model->getTableName() .'_'. $rec ['id'] , 'cell' => $record);
							}else {
								$data['status']=0;
							}
						} else
							$data ['status'] = 0;
						if ($data ['status']) {
							$message .= 'выполнено успешно!';
							$type = 'success';
						}else{
							$this->log('Error '.$mode,Zend_Log::ERR);
							$message .= 'отменено из-за ошибок!';
							$type = 'alert';
						}
						$controler->getHelper('flashMessenger')->setNamespace ( 'messages' )->addMessage ( array ('text' => $message, 'type' => $type ) );
						$module_name = $this->getRequest()->getModuleName();
						$controler_name = $this->getRequest()->getControllerName();
						$controler->getHelper('redirector')->gotoRoute(array('module'=>$module_name,'controller'=>$controler_name,'action'=>'index'),'backend');
					} else
						$controler->view->form = $form;
					
				} else
					$controler->view->form = $form;
			
    		}
    	}
    }
	
}